class Solution {
public:
    int lenLongestFibSubseq(vector<int>& a) {
        int n = a.size();
        unordered_map<int, int>mp;
        for (int i = 0; i < n; i++) mp[a[i]] = i;
        vector<vector<int>>f(n, vector<int>(n, 2));
        int ans = 0;
        for (int j = 2; j < n; j++) {
            for (int i = 1; i < n; i++) {
                int x = a[j] - a[i];
                if (mp.count(x) && x < a[i]) {
                    f[i][j] = f[mp[x]][i] + 1;
                }
                ans = max(ans, f[i][j]);
            }
        }
        return ans < 3 ? 0 : ans;
    }
};